package com.lv.LvTourismOrder.web;
import com.aqgj.User.bean.User;
import com.aqgj.util.JsonWrapper;
import com.aqgj.util.Pager;
import com.aqgj.util.StringUtils;
import com.lv.LvTourismOrder.bean.LvTourismOrder;
import com.lv.LvTourismOrder.service.LvTourismOrderManager;
import com.ztc.ZtcOrder.bean.ZtcOrder;
import com.ztc.ZtcTransport.bean.ZtcTransport;
import com.ztc.ZtcTransport.service.ZtcTransportManager;
import com.ztc.util.excel.ExcelUtil;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("lvTourismOrderAction")
public class LvTourismOrderAction{
    @Autowired
    private LvTourismOrderManager lvTourismOrderManager;
    @Autowired
    private ZtcTransportManager ztcTransportManager;
    private static final Logger log = LogManager.getLogger(ZtcOrder.class);

    /**
     * 下单
     * @param orderInfo 订单信息
     * @param id 在售旅游产品id
     * @param customerInfos 顾客信息
     * @return
     */
    @RequestMapping("sign")
    @ResponseBody
    public HashMap<String, Object> save(String orderInfo, String id, String customerInfos){
        log.info("开始下单");
        HashMap<String, Object> wapper = new HashMap<>();
        String result = lvTourismOrderManager.save(orderInfo,id,customerInfos);
        if ("1".equals(result)) {
            wapper.put("success", Boolean.valueOf(true));
            wapper.put("msg", "下单成功");
            log.info("下单成功");
            return wapper;
        } else if ("01".equals(result)) {
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "儿童位不足");
            log.info("儿童位不足");
            return wapper;
        } else if("02".equals(result)){
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "成人位不足");
            log.info("成人位不足");
            return wapper;
        }else if("03".equals(result)){
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "该旅游产品已停售");
            log.info("该旅游产品已停售");
            return wapper;
        }else if("04".equals(result)){
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "该旅游产品不可加房");
            log.info("该旅游产品不可加房");
            return wapper;
        }else{
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "网络错误，下单失败");
            log.info("网络错误，下单失败");
            return wapper;
        }
    }

    /**
     * 取消
     * @param id 旅游订单id
     * @param refundReason 退单理由
     * @return
     */
    @RequestMapping("cancel")
    @ResponseBody
    public HashMap<String, Object> cancel(String id,String refundReason){
        log.info("开始退单");
        HashMap<String, Object> wapper = new HashMap<>();
        String result = lvTourismOrderManager.cancel(id,refundReason);
        if ("1".equals(result)) {
            wapper.put("success", Boolean.valueOf(true));
            wapper.put("msg", "退单成功");
            log.info("退单成功");
            return wapper;
        } else if ("01".equals(result)) {
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "该单已退");
            log.info("该单已退");
            return wapper;
        } else{
            wapper.put("success", Boolean.valueOf(false));
            wapper.put("msg", "网络错误，退单失败");
            log.info("网络错误，退单失败");
            return wapper;
        }
    }

    /**
     * 获取订单信息
     * @param id 旅游订单id
     * @return
     */
    @RequestMapping("get")
    @ResponseBody
    public HashMap<String, Object> get(String id){
        HashMap<String, Object> wapper = new HashMap<>();
        LvTourismOrder lvTourismOrder=lvTourismOrderManager.get(id);
        wapper.put("success", Boolean.valueOf(true));
        wapper.put("lvTourismOrder", lvTourismOrder);
        return wapper;
    }
    /*@RequestMapping("getList")
    @ResponseBody
    public HashMap<String, Object> getList(String userId,String transportId){
        HashMap<String, Object> wapper = new HashMap<>();
        List<LvTourismOrder> list=lvTourismOrderManager.getList(userId,transportId);
        wapper.put("success", Boolean.valueOf(true));
        wapper.put("list",list);
        return wapper;
    }*/
   /* @RequestMapping("getList")
    @ResponseBody
    public HashMap<String, Object> getList(String pageNumber,String pageSize,String orderNumber,String tourismName,String status,String transportId){
        HashMap<String, Object> wapper = new HashMap<>();
        List<LvTourismOrder> list=lvTourismOrderManager.getList(pageNumber,pageSize,orderNumber,tourismName,status,transportId);
        wapper.put("success", Boolean.valueOf(true));
        wapper.put("list",list);
        int count=lvTourismOrderManager.getCount(orderNumber,tourismName,status,transportId);
        wapper.put("count",count);
        return wapper;
    }*/
    /**
     * 获得当前公司所有订单（旅游）
     * @param session
     * @param pageSize  分页大小
     * @param pageNumber  页码
     * @param orderId    订单编号（搜索）
     * @param departDateStart   出发日期（搜索）
     * @param departDateEnd   出发日期（搜索）
     * @param contactName   联系人（搜索）
     * @param contactPhone  联系电话（搜索）
     * @param startDate  开始时间（搜索）
     * @param endDate    结束时间（搜索）
     * @param orderStatus    订单状态（搜索）
     * @return  	符合条件的所有订单
     */
    @RequestMapping("getList")
    @ResponseBody
    public HashMap<String, Object> getList(HttpSession session, @RequestParam(defaultValue = "10") Integer pageSize,
                                           @RequestParam(defaultValue = "1") Integer pageNumber, String orderId, String startDate, String endDate, String departDateStart, String departDateEnd, String contactName, String contactPhone, String orderStatus) {
        User user=(User)session.getAttribute("userInfo");
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        Pager<Map> lvOrders=lvTourismOrderManager.getList(ztcTransport,pageSize,pageNumber,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
        return JsonWrapper.successPagerWrapper(lvOrders.getContent(),lvOrders.getRecordTotal());
    }
    /**
     * 导出excel，当前页
     * @param response
     */
    @RequestMapping("exportExcel")
    public void exportFeedBack(HttpServletResponse response, HttpSession session, @RequestParam(defaultValue ="1") Integer pageNumber, @RequestParam(defaultValue ="10") Integer pageSize, String orderId, String startDate, String endDate, String departDateStart, String departDateEnd, String contactName, String contactPhone, String orderStatus) {
        User user=(User)session.getAttribute("userInfo");
        String	fileName="订单列表"+System.currentTimeMillis() + ".xls";
        String	sheetName="订单详情";
        //标题
        String[] title = new String[]{"订单号", "订单状态", "订单日期", "出发日期", "出发站", "到达站", "订单金额(元)", "总票数", "姓名", "联系电话", "乘客信息", "退票金额"};
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        Pager<Map> ztcOrders=lvTourismOrderManager.getList(ztcTransport,pageSize,pageNumber,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
        String[][] values = new String[ztcOrders.getContent().size()][];
        for (int i = 0; i < ztcOrders.getContent().size(); i++) {
            values[i] = new String[title.length];
            //将对象内容转换成string
            Map<String, Object> obj = ztcOrders.getContent().get(i);
            values[i][0] = obj.get("order_number").toString();
            values[i][1] = getStatusByInteger(obj.get("status").toString());
            values[i][2] = obj.get("order_time").toString();
            values[i][3] = obj.get("departure_time").toString();
            values[i][4] = obj.get("start_city").toString();
            values[i][5] = obj.get("end_city").toString();
            values[i][6] = obj.get("order_balance").toString();
            values[i][7] = "成人:"+obj.get("remain_seat_number").toString()+"位,儿童:"+obj.get("remain_child_seat_number").toString()+"位";
            values[i][8] = obj.get("contact_name").toString();
            values[i][9] = obj.get("contact_phone").toString();
            values[i][10] = obj.get("pe").toString();
            values[i][11] = obj.get("refund_balance").toString();
        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        ExcelUtil.setResponseHeader(response,fileName,wb);
    }

    /**
     * 导出excel全部数据
     * @param response
     */
    @RequestMapping("exportAllExcel")
    public void exportAllExcel(HttpServletResponse response, HttpSession session,String orderId,String startDate,String endDate,String departDateStart,String departDateEnd,String contactName,String contactPhone,String orderStatus) {
        User user=(User)session.getAttribute("userInfo");
        String	fileName="订单列表"+System.currentTimeMillis() + ".xls";
        String	sheetName="订单详情";
        //标题
        String[] title = new String[]{"订单号", "订单状态", "订单日期", "出发日期", "出发站", "到达站", "订单金额(元)", "总票数", "姓名", "联系电话", "乘客信息", "退票金额"};
        ZtcTransport ztcTransport=ztcTransportManager.get(user.getTransportId());
        List<Map> ztcOrders=lvTourismOrderManager.getList(ztcTransport,orderId,startDate,endDate,departDateStart,departDateEnd,contactName,contactPhone,orderStatus);
        String[][] values = new String[ztcOrders.size()][];
        for (int i = 0; i < ztcOrders.size(); i++) {
            values[i] = new String[title.length];
            //将对象内容转换成string
            Map<String, Object> obj = ztcOrders.get(i);
            values[i][0] = obj.get("order_number").toString();
            values[i][1] = getStatusByInteger(obj.get("status").toString());
            values[i][2] = obj.get("order_time").toString();
            values[i][3] = obj.get("departure_time").toString();
            values[i][4] = obj.get("start_city").toString();
            values[i][5] = obj.get("end_city").toString();
            values[i][6] = obj.get("order_balance").toString();
            values[i][7] = "成人:"+obj.get("remain_seat_number").toString()+"位,儿童:"+obj.get("remain_child_seat_number").toString()+"位";
            values[i][8] = obj.get("contact_name").toString();
            values[i][9] = obj.get("contact_phone").toString();
            values[i][10] = obj.get("pe").toString();
            values[i][11] = obj.get("refund_balance").toString();
        }
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        ExcelUtil.setResponseHeader(response,fileName,wb);
    }

    private String getStatusByInteger(String orderStatus){
        switch (orderStatus){
            case "3":orderStatus="已完成";break;
            case "2":orderStatus="待出行";break;
            case "1":orderStatus="出票中";break;
            case "5":orderStatus="已退款";break;
            case "4":orderStatus="退款中";break;
            case "6":orderStatus="退款失败";break;
            case "0":orderStatus="待支付";break;
        }
        return orderStatus;
    }
    /**
     * 获得订单详情
     * @param orderId 订单id
     * @return
     */
    @RequestMapping("getOrderDetail")
    @ResponseBody
    public HashMap<String, Object> getOrderDetail(String orderId) {
        if(StringUtils.isBlank(orderId)){
            return JsonWrapper.failureWrapperMsg("订单参数异常！");
        }
        LvTourismOrder lvTourismOrder=lvTourismOrderManager.get(orderId);
        if(lvTourismOrder==null){
            return JsonWrapper.failureWrapperMsg("订单详情获取失败！");
        }
        return lvTourismOrderManager.getOrderDetail(orderId);
    }
}